package gui;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dialog;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.DefaultCellEditor;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;

import client.Cart;
import client.Catalog;
import client.ItemsInCustomItem;
import client.LogIn;
import client.Main;
import client.MyTableModel;
import client.ObjHandle;
import client.Order;
import client.RemoveItems;
import client.setImage;

public class Cart_Gui extends JFrame implements ActionListener 
{
	public setImage img = null;
	public JButton logOut = null;
	public JButton Back = null;
	public JButton Submit = null;
	public JLabel userCustomCartl = null;
	public static JTable table = null;
	public static JTable customItemsTable = null;
	public RemoveItems remove = null;
	public JButton removeItem = new JButton();
	public JScrollPane ScrollPane = null;
	public JScrollPane customScrollPane = null;
	public String[] columnNames = {"Id", "Name", "Total Price", "Type", "Quantity", "In/Out Purchase", "Image", "Remove"};
	public String[] customColumnNames = {"Id", "Name", "Total Price", "Type", "In/Out Purchase", "Items in custom", "Remove"};
	public JButton itemsIn = new JButton();
	public JButton removeCustomItem = new JButton();
	public Object[][] customData = null;
	public static Object[][] itemsForOrder = null;
	public static Object[][] customItemsForOrder = null;
	public static String callFrom = null;
	public static ItemsInCustomItem ItemsInCustom = null;
	public Delivery_Greeting_Gui deliveryGreeting = null;
	int width = (int)Main.dim.getWidth();
	int height = (int)Main.dim.getHeight();
	public static float total = 0;
		
	public Cart_Gui(String call)
	{ 
		callFrom = call;
		Object[] temp = null;
		if(Main.cart_Control != null)
			Main.cart_Control = null;
		Main.cart_Control = new Cart("getData", temp);
		Main.cart_Control = (Cart)Main.clie.getResult();
		
		if(Main.cart_Control.dataFromDB.length != 0 || Main.cart_Control.customDataFromDB.length != 0)
		{	
			Main.main.setVisible(false);
			img = new setImage("Cart");
			img.setLayout(null);
			
			this.setTitle("Cart");
			this.setPreferredSize(new Dimension(width-200, height-200));
			this.setLocation((int)Main.dim.getWidth()/2 - (int)this.getPreferredSize().getWidth()/2,(int)Main.dim.getHeight()/2 - (int)this.getPreferredSize().getHeight()/2);
			this.setResizable(false);
			
			final DefaultTableCellRenderer dtcr = new DefaultTableCellRenderer();  
	        dtcr.setHorizontalTextPosition(JLabel.CENTER);  
	        
			table = new JTable(new MyTableModel(Main.cart_Control.dataFromDB, columnNames, "cart"));
		    table.setPreferredScrollableViewportSize(new Dimension(450, 200));
	        table.setFillsViewportHeight(true);
	        table.setFont(new Font (Font.SANS_SERIF ,Font.ITALIC,18));
	        table.setIntercellSpacing(new Dimension(30,30));
			table.getTableHeader().setFont(new Font (Font.SANS_SERIF ,Font.ITALIC,20));
			table.getTableHeader().setForeground(new Color(92,64,51));
	        table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
	        table.getColumnModel().getColumn(0).setCellRenderer(dtcr);
	        table.getColumnModel().getColumn(2).setCellRenderer(dtcr);
	        table.getColumnModel().getColumn(4).setCellRenderer(dtcr);
	        
	        table.setBackground(new Color(253,245,230));
	        table.setRowHeight(100);
	        
	        table.getColumnModel().getColumn(7).setCellRenderer(new ButtonRenderer());
	        table.getColumnModel().getColumn(7).setCellEditor(new ButtonEditor(new JCheckBox()));
	        removeItem.addActionListener(this);
	        
	        ScrollPane = new JScrollPane(table);
	        ScrollPane.setBounds(10, 80, (int)this.getPreferredSize().getWidth()-25, (int)this.getPreferredSize().getHeight()-190);
	        img.add(ScrollPane);
		
			if(Main.cart_Control.DISTINCTcustomDataFromDB.length != 0)
			{
				customData = new Object[Main.cart_Control.DISTINCTcustomDataFromDB.length][7];
				float f = 0;
				int k = 0;
				for(int i = 0 ; i < customData.length ; i++, k++)
				{
					while(Main.cart_Control.customDataFromDB[k][0] == Main.cart_Control.DISTINCTcustomDataFromDB[i])
					{
						f += (Float)Main.cart_Control.customDataFromDB[k][2] * (Integer)Main.cart_Control.QuantityCustomDataFromDB[k];
						k++;
						if(k == Main.cart_Control.customDataFromDB.length)
							break;
					}
					k--;
					customData[i][0] = Main.cart_Control.DISTINCTcustomDataFromDB[i];			//custom item id
					customData[i][1] = Main.cart_Control.DISTINCTcustomDataNameFromDB[i];		//custom item name
					customData[i][2] = f;												//custom item price
					customData[i][3] = Main.cart_Control.customDataFromDB[k][3];					//custom item type
					customData[i][4] = new Boolean(true);								//In/Out Purchase
					customData[i][5] = "items in";										//items in.. button
				    customData[i][6] = "remove";										//remove item button
				    f = 0;
				}
			
				customItemsTable = new JTable(new MyTableModel(customData, customColumnNames, "customCart"));
				customItemsTable.setPreferredScrollableViewportSize(new Dimension(450, 200));
				customItemsTable.setFillsViewportHeight(true);
				customItemsTable.setFont(new Font (Font.SANS_SERIF ,Font.ITALIC,18));
				customItemsTable.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
				customItemsTable.getColumnModel().getColumn(0).setCellRenderer(dtcr);
		        customItemsTable.getColumnModel().getColumn(2).setCellRenderer(dtcr);

		        customItemsTable.setBackground(new Color(253,245,230));
		        customItemsTable.setIntercellSpacing(new Dimension(20,20));
		        customItemsTable.getTableHeader().setFont(new Font (Font.SANS_SERIF ,Font.ITALIC,20));
		        customItemsTable.getTableHeader().setForeground(new Color(92,64,51));
		        customItemsTable.setRowHeight(45);
		        
		        customItemsTable.getColumnModel().getColumn(5).setCellRenderer(new ButtonRenderer());
		        customItemsTable.getColumnModel().getColumn(5).setCellEditor(new ButtonEditor(new JCheckBox()));
		        itemsIn.addActionListener(this);
		        customItemsTable.getColumnModel().getColumn(6).setCellRenderer(new ButtonRenderer());
		        customItemsTable.getColumnModel().getColumn(6).setCellEditor(new ButtonEditor(new JCheckBox()));
		        removeCustomItem.addActionListener(this);
		        
				customScrollPane = new JScrollPane(customItemsTable);
				customScrollPane.setBounds(10, (int)this.getPreferredSize().getHeight()-290, (int)this.getPreferredSize().getWidth()-25, (int)this.getPreferredSize().getHeight()-650);
				img.add(customScrollPane);
				ScrollPane.setBounds(10, 80, (int)this.getPreferredSize().getWidth()-25, (int)this.getPreferredSize().getHeight()-420);
				
				userCustomCartl = new JLabel("Custom Items In Cart:");
				userCustomCartl.setFont(new Font (Font.SANS_SERIF ,Font.BOLD,25));
				userCustomCartl.setBounds(10,(int)this.getPreferredSize().getHeight()-330, 300, 40);
				img.add(userCustomCartl);
			}
			
			Back = new JButton("Back");
			Back.setBounds((int)this.getPreferredSize().getWidth()-115,10,100,40);
			Back.addActionListener(this);
			img.add(Back);
			
			logOut = new JButton("LogOut");
			logOut.setBounds(10,10,100,40);
			logOut.addActionListener(this);
			img.add(logOut);
			
			Submit = new JButton("Submit Cart ( Payment )");
			Submit.setFont(new Font (Font.SANS_SERIF ,Font.PLAIN,20));
			Submit.setBounds(200, (int)this.getPreferredSize().getHeight()-95, (int)this.getPreferredSize().getWidth()-400, 50);
			Submit.addActionListener(this);
			img.add(Submit);
			
			this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
			this.add(img);
			this.pack();
			
			this.setEnabled(true);
			this.setVisible(true);
		}	
		else
		{
			JOptionPane.showMessageDialog(null,"No items in cart","ERROR",JOptionPane.ERROR_MESSAGE);	
			
			if(callFrom.equals("MainScreen"))
			{
				Main.main.setEnabled(true);
				Main.main.setVisible(true);
			}
			else 
				if(callFrom.equals("Catalog"))
				{
					if(Main.catalog != null)
						Main.catalog.dispose();
					Main.catalog = new Catalog("MainScreen");		
				}
			else 
				if(callFrom.equals("CustomOrder"))
				{
					Main.catalog.setEnabled(true);
					Main.catalog.setVisible(true);
				}
			this.dispose();
		}
	}
	
	public void actionPerformed(ActionEvent e) 
	{
		if(e.getSource() == Submit)
		{	
			itemsForOrder = new Object[Main.cart_Control.dataFromDB.length][5]; 
			
			for(int i = 0 ; i < Main.cart_Control.dataFromDB.length ; i++)
				if((Boolean)table.getValueAt(i, 5) == true)
				{
					for(int j = 0 ; j < 5 ; j++)
						itemsForOrder[i][j] = table.getValueAt(i, j);
					total+= (Float)itemsForOrder[i][2];
				}
			customItemsForOrder = new Object[Main.cart_Control.DISTINCTcustomDataFromDB.length][4]; 
			
			for(int i = 0 ; i < Main.cart_Control.DISTINCTcustomDataFromDB.length ; i++)
				if((Boolean)customItemsTable.getValueAt(i, 4) == true)
				{
					for(int j = 0 ; j < 4 ; j++)
						customItemsForOrder[i][j] = customItemsTable.getValueAt(i, j);
					total+= (Float)customItemsForOrder[i][2];
				}
			
			deliveryGreeting = new Delivery_Greeting_Gui();
			this.setEnabled(false);
		}
		
		if(e.getSource() == removeItem)
		{	
			if(remove != null)
				remove.dispose();
			remove = new RemoveItems("userCart");
		}
		
		if(e.getSource() == itemsIn)
		{		
			int customItemId = (Integer)customItemsTable.getValueAt(customItemsTable.getSelectedRow(), 0);	
		 	Object[] temp = new Object[1];
		 	temp[0] = customItemId;
		 	Main.cart_Control = new Cart("getItemsInCustomItem", temp);
		 	Main.cart_Control = (Cart)Main.clie.getResult();
			
			if(ItemsInCustom != null)
				ItemsInCustom.dispose();
			ItemsInCustom = new ItemsInCustomItem(Main.cart_Control.itemsInCustomItemFromDB);
			this.setVisible(false);
		}
		
		if(e.getSource() == removeCustomItem)
		{	
			int msg = JOptionPane.showConfirmDialog(null, "Are you sure you want to remove this item? ","Confirmation" ,JOptionPane.OK_CANCEL_OPTION);
   		 	if(msg == 0)		//CANCEL = 2 //OK = 0	
   		 	{
   		 		int customItemIdToRemove = (Integer)customItemsTable.getValueAt(customItemsTable.getSelectedRow(), 0);
   		 		
   		 		Object[] temp = new Object[1];
   		 		temp[0] = customItemIdToRemove;
   		 		Main.cart_Control = new Cart("removeCustomData", temp);
   		 		int result = (Integer)Main.clie.getResult();
   		 		System.out.println(result);
   		 		
   		 	if(callFrom.equals("MainScreen"))
				Main.main.cart.doClick();

			else if(callFrom.equals("Catalog"))
					Main.catalog.goToCart.doClick();		
			
			else if(callFrom.equals("CustomOrder"))
					Main.customOrder.goToCart.doClick();
   		 	}
		}
		
		if(e.getSource() == Back)
		{			
			if(callFrom.equals("MainScreen"))
			{
				Main.main.showMainScreen();
			}
			else 
				if(callFrom.equals("Catalog"))
				{
					if(Main.catalog != null)
						Main.catalog.dispose();
					Main.catalog = new Catalog("MainScreen");		
				}
			else 
				if(callFrom.equals("CustomOrder"))
				{
					Main.catalog.setEnabled(true);
					Main.catalog.setVisible(true);
				}
			this.dispose();
		}
		if(e.getSource() == logOut)
		{
			if(JOptionPane.showConfirmDialog(null,"Are you sure you want to logout?",null,JOptionPane.YES_NO_OPTION)==JOptionPane.YES_OPTION)
			{
				this.setEnabled(false);
				this.setVisible(false);
				Main.main.logOut.doClick();
			}
		}
	}
	
	class ButtonRenderer extends JButton implements TableCellRenderer 
    {
    	public ButtonRenderer() 
    	{setOpaque(true);}
    	public Component getTableCellRendererComponent(JTable table, Object value,boolean isSelected, boolean hasFocus, int row, int column)
    	{
    		if(column == 5)	
    			setText("Items in custom");
    		else if(column == 6 || column == 7)
    			setText("Remove");
    		
    		return this;
    	}
    }
    
    class ButtonEditor extends DefaultCellEditor 
    {
    	private String label;
    	public ButtonEditor(JCheckBox checkBox) 
    	{
    		super(checkBox);
    	}
    	public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) 
    	{
    		if(column == 5)	
    		{
    			label = "Items in custom";
    			itemsIn.setText(label);
    			return itemsIn;
    		}
    		else if(column == 6)
    		{
        		label = "Remove";
        		removeCustomItem.setText(label);
        		return removeCustomItem;
        	}
    		else //(column == 7)
    		{
        		label = "Remove";
        		removeItem.setText(label);
        		return removeItem;
        	}
    	}
    	public Object getCellEditorValue() 
    	{
    		return new String(label);
    	}
    }
}
